<template lang="pug">
.view.cp-purchase-order.fix-flex-pos
  //- 查询
  el-form.pe-search(:inline="true")
    el-form-item
      el-select(v-model="orderDateType", placeholder="请选择", style="width: 108px")
        el-option(key="0", label="创建时间", :value="0")
        el-option(key="1", label="提交时间", :value="1")
        el-option(key="2", label="审批时间", :value="2")
    el-form-item
      el-date-picker(
        v-model="orderDate"
        type="daterange"
        :clearable="false"
        style="width: 256px"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期")
    el-button(type="primary", @click="resetTime", plain, style="margin-right: 16px") 重置时间
    el-form-item(label="保单号 : ")
      el-input(v-model="orderOrder", placeholder="采购订单号", style="width: 160px")
    el-form-item(label="状态 : ")
      el-select(v-model="orderStatus", placeholder="请选择", style="width: 120px")
        el-option(
          v-for="item in statusSelectAll",
          :key="item.value",
          :label="item.name",
          :value="item.value")
    el-form-item(label="供应商 : ")
      el-select(v-model="orderSupply", placeholder="请选择", style="width: 120px")
        el-option(
          v-for="item in supplySelectAll",
          :key="item.value",
          :label="item.name",
          :value="item.value")
    el-form-item(label="创建人 : ")
      el-select(v-model="orderBuyer", placeholder="请选择", style="width: 120px")
        el-option(
          v-for="item in empSelectAll",
          :key="item.value",
          :label="item.name",
          :value="item.value")
    el-button(type="primary", @click="searchOrders") 搜索
    el-button(type="primary", @click="resetSearch", plain) 重置
    el-button(type="primary", @click="addOrder") 新建采购订单
    //- el-form-item
    //-   el-button(type="primary") 导出
  //- 列表
  .pe-table
    el-table(:data="purorders", height="100%", highlight-current-row, size="mini", v-loading="loadingOrders")
      el-table-column(align="center", show-overflow-tooltip, type="index", :index="indexMethod", label="序号", :fixed="true")
      el-table-column(align="center", label="采购单号")
        template(slot-scope="scope")
          el-tooltip(
            effect="dark"
            placement="top"
            :content="scope.row.order")
            div.cell.el-tooltip(style="padding: 0") {{scope.row.order}}
      el-table-column(align="center", show-overflow-tooltip, prop="status", label="状态")
        template(slot-scope="scope")
          span {{ scope.row.status | compare-list(statusSelectAll) }}
      el-table-column(align="center", show-overflow-tooltip, prop="supply", label="供应商")
        template(slot-scope="scope")
          span {{ scope.row.supply | compare-list(supplySelect) }}
      el-table-column(align="center", show-overflow-tooltip, prop="creator", label="创建人")
        template(slot-scope="scope")
          span {{ scope.row.creator | compare-list(empSelect) }}
      el-table-column(align="center", show-overflow-tooltip, prop="createTime", label="创建时间")
        template(slot-scope="scope")
          span {{ scope.row.createTime | date-format }}
      el-table-column(align="center", show-overflow-tooltip, prop="approveTime", label="批准时间")
        template(slot-scope="scope")
          span {{ scope.row.approveTime | date-format }}
      el-table-column(align="center", show-overflow-tooltip, prop="orderTime", label="下单时间")
        template(slot-scope="scope")
          span {{ scope.row.orderTime | date-format }}
      el-table-column(align="center", show-overflow-tooltip, prop="stateTime", label="结单时间")
        template(slot-scope="scope")
          span {{ scope.row.stateTime | date-format }}
      el-table-column(align="center", show-overflow-tooltip, prop="comment", label="备注")
      el-table-column(align="center", label="操作", min-width="110px")
        template(slot-scope="scope")
          el-tooltip(content="查看")
            i.icon-act.el-icon-view(@click="viewOrder(scope.row)")
          el-tooltip(content="编辑")
            i.icon-act.el-icon-edit(@click="eidtOrder(scope.row, scope.$index)")
          el-tooltip(content="复制")
            i.icon-act.el-icon-hy-copy(@click="copyOrder(scope.row)")
          el-dropdown
            i.icon-act.el-icon-more
            el-dropdown-menu(slot="dropdown", class="pe-act-drop")
              el-dropdown-item.act-item(@click.native="submitOrder(scope.row)", :disabled="scope.row.status > 0")
                i.icon-act.el-icon-hy-submit-o
                span 提交
              el-dropdown-item.act-item(@click.native="backOrder(scope.row)", :disabled="scope.row.status != 1")
                i.icon-act.el-icon-hy-back
                span 撤回
              el-dropdown-item.act-item(@click.native="openPlace(scope.row)")
                i.icon-act.el-icon-sold-out
                span 下单
              el-dropdown-item.act-item(@click.native="viewOrder(scope.row, true)")
                i.icon-act.el-icon-check
                span 结单
              el-dropdown-item.act-item(@click.native="deleteOrder(scope.row, scope.$index)")
                i.icon-act.el-icon-delete
                span 删除
              el-dropdown-item.act-item(@click.native="yetOrder(scope.row, scope.$index)")
                i.icon-act.el-icon-success
                span 已采购
  //- 分页
  el-pagination.pe-pagination(
    layout="total, prev, pager, next, jumper",
    @current-change="changeOrderPage",
    :current-page.sync="currentPage",
    :page-size="pageSize",
    :total="purordersTotal")
  OrderPlace(:visible="showOrderPlace", :order="passOrder", :supply="passSupply", @close="showOrderPlace=false", @place="placeOrder")
  OrderView(:visible="showOrderView", :formData="formData", :isFinish="isFinish", @close="showOrderView=false", @state="stateOrder")
  OrderEdit(:visible="showOrderEdit", :formData="formData", @close="showOrderEdit=false", @save="saveOrder")
</template>

<script>
import { mapGetters } from 'vuex';
import ComApi from '@/api/common';
import PurApi from '@/api/purchase';
import OrderView from '@/components/purchase/order/OrderView';
import OrderEdit from '@/components/purchase/order/OrderEdit';
import OrderPlace from '@/components/purchase/order/OrderPlace';

export default {
  name: 'purorder',
  components: {
    OrderView,
    OrderEdit,
    OrderPlace
  },
  data() {
    return {
      // 搜索条件
      orderDateType: 0,
      orderDate: [],
      orderOrder: '',
      orderStatus: null,
      orderSupply: null,
      orderBuyer: null,
      orderCreator: null,
      //
      purorders: [],
      purordersTotal: 1,
      loadingOrders: true,
      currentPage: 1,
      pageSize: 20,
      // 物料
      activeTabIndex: '0',
      tabShows: [true, false, false, false],
      statusSelectAll: [],
      // 结单
      isFinish: false,
      formData: {
        materiels: [],
        finances: [],
        terms: [],
        bills: []
      },
      showOrderView: false,
      showOrderEdit: false,
      passOrder: null,
      passSupply: null,
      showOrderPlace: false
    };
  },
  computed: {
    ...mapGetters(['empSelect', 'empSelectAll', 'oneDeptSelect', 'supplySelect', 'supplySelectAll', 'employeeId'])
  },
  methods: {
    indexMethod (i) {
      return ((this.currentPage - 1) * this.pageSize) + (i + 1);
    },
    resetTime () {
      this.orderDate = [];
    },
    resetSearch () {
      this.orderDateType = 0;
      this.orderDate = [];
      this.orderOrder = '';
      this.orderStatus = null;
      this.orderSupply = null;
      this.orderCreator = null;
      this.$message.success('重置成功');
    },
    makeSearch () {
      const params = {};
      const dates = this.orderDate.map(date => date.valueOf());
      const datePros = [
        ['startCreationTime', 'endCreationTime'],
        ['startSubmissionTime', 'endSubmissionTime'],
        ['startApprovalTime', 'endApprovalTime']
      ];
      if (dates.length) {
        params[datePros[this.orderDateType][0]] = dates[0];
        params[datePros[this.orderDateType][1]] = dates[1];
      }
      if (this.orderOrder) {
        params.order = this.orderOrder;
      }
      if (typeof this.orderStatus !== 'object') {
        params.status = this.orderStatus;
      }
      if (this.orderSupply) {
        params.supply = this.orderSupply;
      }
      if (this.orderBuyer) {
        params.creator = this.orderBuyer;
      }

      return params;
    },
    searchOrders () {
      const params = this.makeSearch();
      this.loadingOrders = true;
      PurApi.getPurchaseOrder(params).then((result) => {
        if (!result.status) {
          this.purorders = result.obj.records;
          this.purordersTotal = result.obj.totalNum;
        } else {
          this.purorders = [];
          this.purordersTotal = 1;
        }
        this.currentPage = 1;
        this.loadingOrders = false;
      }).catch((error) => {
        this.loadingOrders = false;
        console.log(JSON.stringify(error));
      });
    },
    // 监听Order列表事件
    handleOrderRowDbClick (row) {
      this.viewOrder(row);
    },
    // 监听对Order条目操作事件
    addOrder () {
      this.formData = Object.assign({}, {
        materiels: [],
        finances: [],
        terms: [],
        bills: []
      });
      this.showOrderEdit = true;
    },
    viewOrder (row, isFinish) {
      PurApi.getOrderDetail({ id: row.order }).then((result) => {
        if (!result.status) {
          this.showOrderView = true;
          this.formData = result.obj;
          this.isFinish = isFinish;
          if (isFinish) {
            this.stateRow = row;
            this.finishRow = row;
          }
        } else {
          this.$message.error(result.comment);
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
      });
    },
    eidtOrder (row, index) {
      this.focusIndex = index;
      PurApi.getOrderDetail({ id: row.order }).then((result) => {
        if (!result.status) {
          this.formData = result.obj;
          this.showOrderEdit = true;
        } else {
          this.$message.error(result.comment);
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
      });
    },
    copyOrder (row) {
      PurApi.getOrderDetail({ id: row.order }).then((result) => {
        if (!result.status) {
          this.formData = result.obj;
          this.formData.order = null;
          this.showOrderEdit = true;
        } else {
          this.$message.error(result.comment);
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
      });
    },
    submitOrder (row) {
      PurApi.submitOrder({ id: row.order }).then((result) => {
        if (!result.status) {
          row.status = '1';
          row.submitTime = Date.now();
          this.$message.success('提交成功');
        } else {
          this.$message.error(`提交失败：${result.comment}`);
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
      });
    },
    openPlace (row) {
      this.showOrderPlace = true;
      this.stateRow = row;
      this.passOrder = row.order;
      this.passSupply = row.supply;
    },
    placeOrder (params) {
      PurApi.placeOrder(params).then((result) => {
        if (!result.status) {
          this.stateRow.status = result.obj.status;
          this.stateRow.orderTime = result.obj.orderTime;
          this.showOrderPlace = false;
          this.$message.success('下单成功');
        } else {
          this.$message.error(`下单失败：${result.comment}`);
        }
      }).catch((error) => {
        this.showOrderPlace = false;
        console.log(JSON.stringify(error));
      });
    },
    stateOrder (isNormal, content) {
      const row = this.stateRow;
      PurApi.stateOrder({
        isNormal,
        orderId: row.order,
        content
      }).then((result) => {
        if (!result.status) {
          this.$message.success('结单成功');
          this.finishRow.stateTime = result.obj.stateTime;
          this.finishRow.status = result.obj.status;
          this.showOrderView = false;
        } else {
          this.$message.error(`结单失败：${result.comment}`);
        }
      }).catch((error) => {
        this.$message.error('结单失败');
        console.log(JSON.stringify(error));
      });
    },
    backOrder (row) {
      PurApi.backOrder({ id: row.order }).then((result) => {
        if (!result.status) {
          row.status = '0';
          row.submitTime = null;
          this.$message.success('撤回成功');
        } else {
          this.$message.error(`撤回失败：${result.comment}`);
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
      });
    },
    yetOrder (row) {
      PurApi.yetOrder({ id: row.order }).then((result) => {
        if (!result.status) {
          row.status = '0';
          this.$message.success('执行已采购状态变更成功');
        } else {
          this.$message.error(`执行已采购状态变更失败：${result.comment}`);
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
      });
    },
    deleteOrder (row, index) {
      this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loadingOrders = true;
        PurApi.deleteOrder({ id: row.order }).then((result) => {
          this.loadingOrders = false;
          if (!result.status) {
            this.purorders.splice(index, 1);
            this.purordersTotal = this.purordersTotal - 1;
            this.$message.success('删除成功');
          } else {
            this.$message.error(`删除失败：${result.comment}`);
          }
        }).catch((error) => {
          console.log(JSON.stringify(error));
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    saveOrder (formData) {
      PurApi.saveOrder(formData).then((result) => {
        if (!result.status) {
          // 说明为新增
          if (!formData.order) {
            this.purorders.unshift({});
            this.$set(this.purorders, 0, result.obj);
            this.purordersTotal = this.purordersTotal + 1;
          } else {
            this.$set(this.purorders, this.focusIndex, result.obj);
          }
          this.showOrderEdit = false;
          this.$message.success('保存成功');
        } else {
          this.$message.error(`保存失败：${result.comment}`);
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
      });
    },
    // 监听计划翻页
    changeOrderPage (currentPage) {
      const params = this.makeSearch();
      params.pageNum = currentPage;
      this.loadingOrders = true;
      PurApi.getPurchaseOrder(params).then((result) => {
        this.purorders = result.obj.records;
        this.purordersTotal = result.obj.totalNum;
        this.currentPage = currentPage;
        this.loadingOrders = false;
      }).catch((error) => {
        this.loadingOrders = false;
        console.log(JSON.stringify(error));
      });
    }
  },
  created () {
    // 状态列表
    ComApi.getStatus({ orderType: 'procurementorder' }).then((statusList) => {
      this.statusSelectAll = [{ name: '全部', value: null }].concat(statusList);
    });
  },
  mounted () {
    // 取得默认状态下所有计划
    PurApi.getPurchaseOrder().then((result) => {
      this.purorders = result.obj.records;
      this.purordersTotal = result.obj.totalNum;
      this.loadingOrders = false;
    }).catch((error) => {
      this.loadingOrders = false;
      console.log(JSON.stringify(error));
    });
    //
  }
};
</script>

<style lang="sass">
@import "../../../styles/utils"
.cp-purchase-order
  .pr-dialog
    .pr-tabs
      position: relative
      height: 40px
      background: white
      padding-left: 20px
    .pr-finish
      text-align: left
      margin-bottom: 16px
      span
        margin-right: 8px
  .tab-bill
    p
      text-align: right
      margin-top: 12px
      padding-right: 32px
      font-size: 12px
      color: #909399
      font-weight: 500
</style>
